var express = require('express');
var router = express.Router();
let multiparty = require('multiparty');
const SMSClient = require('@alicloud/sms-sdk');
let fs = require('fs')
let { useModel, useZenModel, fansModel, evaluateModel, zjlMy_InformationModel,
  BarkCardsModel, Bark_cardModel, useStatus, useWay, useInquiry, useGrab, usePatientList
  , useFollowup, alldoctorsModel, allGhyyModel, hcy_xiaoxModel, RxModel
  , phtypemodel, phmodel, cfmodel, cfymodel, btmodel } = require("../model/model")
//上传图片
router.post('/upload', (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = 'upload'
  form.parse(req, (err, a, img) => {
    let url = `http://127.0.0.1:3000/${img.image[0].path}`
    zjlMy_InformationModel.create({ path: url })
    res.send({
      code: 200,
      message: "上传成功",
    })
  })
})

// 添加患者消息---黄朝阳
router.post("/addhcy_xiaox", async (req, res) => {
  await hcy_xiaoxModel.create(req.body)
  res.send({
    code: 200,
    mas: "添加成功"
  })
})

// 获取所有的患者消息---黄朝阳
router.get("/gethcy_xiaox", async (req, res) => {
  let data = await hcy_xiaoxModel.find()
  res.send({
    code: 200,
    message: "获取患者消息",
    data
  })
})

// 获取图片
router.post('/getimg', async (req, res) => {
  let imglist = await zjlMy_InformationModel.find()
  res.send({
    code: 200,
    imglist
  })
})
// 注册用户
router.post("/addUser", async (req, res) => {
  await useModel.create(req.body)
  res.send({
    code: 200,
    message: "注册成功"
  })
})
// 登录
// 添加医师认证---在用户登录验证后判断status是否为true，如果是的话跳转到医生认证页面，然后将用户的id和名称添加到本地存储中
router.post("/adduseZen", async (req, res) => {
  await useZenModel.create(req.body)
  res.send({
    code: 200,
    message: "添加医师认证成功"
  })
})
// 添加医生认证中的医院信息---黄朝阳
router.post("/adddoctor", async (req, res) => {
  await alldoctorsModel.create(req.body)
  res.send({
    code: 200,
    message: "添加医院成功"
  })
})
//获取医生认证中所有的医院信息---黄朝阳
router.get("/getdoctors", async (req, res) => {
  let data = await alldoctorsModel.find()
  res.send({
    code: 200,
    message: "获取医院信息成功",
    data
  })
})
// 图片上传---黄朝阳
router.post("/addupload", (req, res) => {
  let form = new multiparty.Form();
  form.uploadDir = "upload"
  form.parse(req, (err, imgData, fileData) => {
    const img = imgData.img[0]
    const file = imgData.file[0]
    let filepath = "./upload/" + img
    const base64Image = file.replace(/^data:image\/jpeg;base64,/, "");
    const buffer = Buffer.from(base64Image, 'base64');
    fs.writeFileSync(filepath, buffer)
    const imageUrl = `/upload/${img}`;
    res.send({
      code: 200,
      msg: "图片上传成功",
      imageUrl
    })
  })
})
//添加挂号预约--黄朝阳
router.post("/addGhyy", async (req, res) => {
  await allGhyyModel.create(req.body)
  res.send({
    code: 200,
    msg: "添加成功"
  })
})
// 获取所有挂号预约数据---黄朝阳
router.get("/getGhyy", async (req, res) => {
  let data = await allGhyyModel.find()
  res.send({
    code: 200,
    msg: "获取数据成功",
    data
  })
})
router.get("/getstatus", async (req, res) => {//获取状态表
  let data = await useStatus.find()
  res.send({
    code: 200,
    message: "获取状态成功",
    data: data
  })
})
router.get("/getway", async (req, res) => {//获取问诊方式表
  let data = await useWay.find()
  res.send({
    code: 200,
    message: "获取问诊方式表成功",
    data: data
  })
})
router.get("/getinquiry", async (req, res) => {//获取问诊列表
  let data = await useInquiry.find().populate('sid').populate('wid')
  res.send({
    code: 200,
    message: "获取问诊列表成功",
    data: data
  })
})
router.get("/getgrab", async (req, res) => {//获取抢单列表
  let { page, limit } = req.query
  let data = await useGrab.find().skip((page - 1) * limit).limit(limit)
  let total = await useGrab.countDocuments()
  console.log(data)
  res.send({
    code: 200,
    message: "获取抢单列表成功",
    data: data,
    total
  })
})
router.get("/getpatientlist", async (req, res) => {//获取患者列表
  let data = await usePatientList.find().populate('sid').populate('wid')
  res.send({
    code: 200,
    message: "获取患者列表成功",
    data: data
  })
})
router.get("/getfollowup", async (req, res) => {//获取复诊列表
  let data = await useFollowup.find().populate('sid')
  res.send({
    code: 200,
    message: "获取复诊列表成功",
    data: data
  })
})

//添加粉丝
router.post('/zjl_addfans', async (req, res) => {
  await fansModel.create(req.body)
  res.send({
    code: 200,
    message: "添加粉丝成功"
  })
})
//获取粉丝
router.get('/zjl_getfans', async (req, res) => {
  let { current } = req.query
  let pagesize = 5
  let fans = await fansModel.find().skip((current - 1) * pagesize).limit(pagesize)
  let pages = await fansModel.find()
  res.send({
    fans,
    pages
  })
})
//获取评价
router.get('/zjl_getevaluate', async (req, res) => {
  let { current } = req.query
  let pagesize = 5
  let evluate = await evaluateModel.find().skip((current - 1) * pagesize).limit(pagesize)
  let pages = await fansModel.find()
  res.send({
    evluate,
    pages
  })
})
//添加评价
router.post('/zjl_addevaluate', async (req, res) => {
  await evaluateModel.create(req.body)
  res.send({
    code: 200,
    message: "添加评价成功"
  })
})

router.get("/uselist", async (req, res) => {
  // let data=await useModel.find()
  let data = {
    name: "admin",
    age: 18
  }
  res.send({
    code: 200,
    data: data
  })
})

//获取手机号
router.get('/user_phone', async (req, res) => {
  let list_phone = await useModel.find()
  res.send({
    list_phone
  })
})
// 阿里云短信配置
const accessKeyId = 'LTAI5tBuvPmqoAp4toBwLyzQ';
const secretAccessKey = 'kjvw6077CJbEZ9kKEDkc0fmGhc1pZh';
const client = new SMSClient({ accessKeyId, secretAccessKey });

// 生成随机验证码
const generateVerificationCode = () => Math.floor(100000 + Math.random() * 900000).toString();

// 验证码接口
router.get('/kwl_getCode', (req, res) => {
  const phone = req.query.phone;
  const code = generateVerificationCode();
  console.log(code);
  client.sendSMS({
    PhoneNumbers: phone,
    SignName: '自主学习',
    TemplateCode: 'SMS_472390011',
    TemplateParam: JSON.stringify({ code }),
  })
    .then(response => {
      const { Code } = response;
      if (Code === 'OK') {
        res.send(JSON.stringify(code));
      } else {
        res.status(500).json({ message: `Failed to send verification code: ${Code}` });
      }
    })
    .catch(err => {
      console.error(err);
      res.status(500).json({ message: 'Failed to send verification code' });
    });
});

//修改手机号
router.post('/update_phone', async (req, res) => {
  let { phone, id } = req.body
  await useModel.updateOne({ id }, { phone })
  res.send({
    code: 200,
    msg: '修改成功'
  })

})

//添加银行卡类别
router.post('/add_bank', async (req, res) => {
  await Bark_cardModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})
//获取银行卡类别
router.get('/get_bank', async (req, res) => {
  const bank = await Bark_cardModel.find()
  res.send({
    bank
  })
})
//添加银行卡
router.post('/add_bankcard', async (req, res) => {
  await BarkCardsModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})
//获取银行卡
router.get('/get_bankcard', async (req, res) => {
  const bankcard = await BarkCardsModel.find().populate('bark')
  res.send({
    bankcard
  })
})


//修改银行卡状态
router.post('/update_bankZt', async (req, res) => {
  let { _id, zt } = req.body
  await BarkCardsModel.updateOne({ _id }, { zt })
  res.send({
    code: 200,
    msg: '修改成功'
  })
})



//获取Id 
router.post('/get_id', async (req, res) => {
  let { id } = req.body
  const data = await fansModel.find({ _id: id })
  res.send({
    code: 200,
    data
  })
})
//查询处方
router.get("/tmbrxlist", async (req, res) => {
  let data = await RxModel.find()
  res.send({
    code: 200,
    data
  })
})

//修改密码
router.post('/update_Mima', async (req, res) => {
  let { id, old_pass } = req.body
  await useModel.updateOne({ _id: id }, { password: old_pass })
  res.send({
    code: 200,
    msg: '修改成功'
  })
})
router.post("/tmbrxadd", (req, res) => {
  RxModel.create(req.body)
  res.send({
    code: 200,
    message: "添加成功"
  })
})
// 添加用药类型
router.post('/mxd_/addtype', (req, res) => {
  let info = req.body

phtypemodel.create(info)


res.send({
  code: 200,
  msg: '添加成功'
})
})

// 获取药品类型
router.get('/mxd_getlist', async (req, res) => {
  let data = await phtypemodel.find()
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
})
// 不同类型药品添加
router.post('/mxd_addbt', (req, res) => {
  let info = req.body


  btmodel.create(info)
  res.send({
    code: 200,
    msg: '不同类型药品添加成功'
  })
})
// 根据Id获取不同类型药品获取
router.get('/mxd_getbt', async (req, res) => {
  let id = req.query.id
  let val = req.query.val
  console.log(val);

  // console.log(id,'845120');

  let name = new RegExp(val, 'i')
  try {
    let query = {}
    if (req.query.id) {
      query.pid = req.query.id
    }
    if (req.query.val) {
      const regex = new RegExp(req.query.val, 'i')
      query.name = { $regex: regex }
    }
    console.log(query);

    const data = await btmodel.find(query)
    res.send({
      code: 200,
      msg: '获取成功',
      data
    })
  } catch (error) {
    res.send({
      code: 500,
      msg: '服务器内部错'
    })
  }





})
// 添加药品
router.post('/mxd_addph', (req, res) => {
  let info = req.body


  phmodel.create(info)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})

// 获取药品
router.get('/mxd_getoh', async (req, res) => {
  let data = await phmodel.find()
  res.send({
    code: 200,
    msg: '获取成功',
    data
  })
})

// 根据ID获取单个药品
router.get('/mxd_getinfo', async (req, res) => {
  let id = req.query.id
  let info = await phmodel.findOne({ _id: id })
  res.send({
    code: 200,
    data: info
  })
})
// 根据typeid获取对应的药品
router.get('/mxd_getidy', async (req, res) => {
  let id = req.query.id
  let value = req.query.val
  let name = new RegExp(value, 'i')
  if (value != '') {
    let data = await phmodel.find({ typeid: id, name: name })
    res.send({
      code: 200,
      data
    })
  } else {
    let data = await phmodel.find({ typeid: id })
    res.send({
      code: 200,
      data
    })
  }

})

// 修改是否为常用药
router.post('/mxd_upy', async (req, res) => {
  let id = req.body._id


  await phmodel.updateOne({ _id: id }, req.body)
  res.send({
    code: 200,
    msg: '修改成功'
  })
})
// 删除药品
router.get('/mxd_delyp', async (req, res) => {
  let id = req.query.id


  await phmodel.deleteOne({ _id: id })
  res.send({
    code: 200,
    msg: '删除成功'
  })
})
// 添加处方
router.post('/mxd_addcf', (req, res) => {
  let info = req.body


  cfmodel.create(info)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})
// 获取处方
router.get('/mxd_getcf', async (req, res) => {
  let data = await cfmodel.find()
  res.send({
    code: 200,
    data
  })
})
// 删除处方
router.get('/mdx_sccf', async (req, res) => {
  let id = req.query.id
  await cfmodel.deleteOne({ _id: id })
  res.send({
    code: 200,
    msg: '删除处方成功'
  })
})
// 修改为常用药
router.post('/mxd_cf', async (req, res) => {
  let id = req.body._id


  await cfmodel.updateOne({ _id: id }, req.body)
  res.send({
    code: 200,
    msg: '修改成功'
  })

})
// 处方详情
router.get('/mxd_infoid', async (req, res) => {
  let id = req.query.id


  let info = await cfmodel.findOne({ _id: id })
  res.send({
    code: 200,
    msg: '获取处方详情',
    data: info
  })
})
// 添加处方药
router.post('/mxd_addcfy', (req, res) => {
  let info = req.body
  console.log(info);

  cfymodel.create(info)
  res.send({
    code: 200,
    msg: '添加成功处方药'
  })
})


// 获取处方药
router.get('/mxd_getcfy', async (req, res) => {
  let data = await cfymodel.find()
  res.send({
    code: 200,
    data
  })
})

// 修改处方药
router.post('/mxd_upcfinfo', async (req, res) => {
  let id = req.body._id
  console.log(req.body);

  await cfmodel.updateOne({ _id: id }, req.body)
  res.send({
    code: 200,
    msg: '处方 修改成功'
  })
})
// 根据处方ID获取相应的处方药
router.get('/mxd_getids', async (req, res) => {
  let id = req.query.id
  let data = await cfymodel.find({ yid: id })

  res.send({
    code: 200,
    data
  })

})


// 根据处方药id获取对应的数据
router.get('/mxd_infoidy', async (req, res) => {
  let id = req.query.id
  let data = await cfymodel.findOne({ _id: id })



  res.send({
    code: 200,
    msg: '获取成功',
    data
  })

})

// 修改处方药
router.post('/mxd_updatecfy', async (req, res) => {
  let { id, nums } = req.body
  console.log(id, nums);



  await cfymodel.updateOne({ _id: id }, { nums: nums })
  res.send({
    code: 200,
    msg: '修改成功'

  })
})


// 删除处方药
router.get('/mxd_sccfyid', async (req, res) => {
  let id = req.query.id
  await cfymodel.deleteOne({ _id: id })
  res.send({
    code: 200,
    msg: '删除成功！！'
  })
})
module.exports = router;
